#!/usr/bin/perl
use strict;
use DBI;
use File::Basename;
use File::Temp qw/tempdir/;
use Sys::Hostname;

# load config
if(-f "$ENV{HOME}/.bictransfer") {
	{ package Settings; do "$ENV{HOME}/.bictransfer" }
}
if (!defined %Settings::db) {
    print "\n\tERROR: Config file error - could not load config settings\n\n"; exit 33;
} 

my $dbh = DBI->connect(&Settings::dbiConnect()) or die "Failed to connect to tarchive db";

my $sth = $dbh->prepare("SELECT TarchiveID, ArchiveLocation FROM tarchive WHERE PendingTransfer=1");
$sth->execute();

if($sth->rows > 0) {
	while(my $row = $sth->fetchrow_hashref()) {
		my $dir = basename(dirname($row->{'ArchiveLocation'}));
		if(system("ssh -x $Settings::transferServer mkdir -p incoming/$dir")) {
			reportError($row);
		} else {
			
			my @cmd = ("scp", "-q", $row->{'ArchiveLocation'}, $Settings::transferServer.":incoming/$dir");
			if(system(@cmd)) {
				reportError($row);
			} else {
				$dbh->do("UPDATE tarchive SET PendingTransfer=0, DateSent=NOW() WHERE TarchiveID=".$dbh->quote($row->{'TarchiveID'}));
			}
		}
	}
}
$sth->finish();
$dbh->disconnect();

my $tempdir = tempdir(CLEANUP=>1);
my $cmd = "/usr/local/mysql/bin/mysqldump -t -n -q --host='$Settings::db{'host'}' --user='$Settings::db{'username'}' --password='$Settings::db{'password'}' $Settings::db{'database'} | gzip > $tempdir/tarchive_data.sql.gz";
my $output = `$cmd`;
unless($?) {
    my @scpcmd = ("scp", "-q", "$tempdir/tarchive_data.sql.gz", $Settings::transferServer.":incoming/tarchive_data.sql.gz");
    system(@scpcmd);
} else {
    print "Failed to dump database.\n$output\n";
}

sub reportError {
	my $row = shift;

	open ERRORLOG, ">> TRANSFER_ERROR.log";
	print ERRORLOG $row->{'TarchiveID'}."\n";
	close ERRORLOG;
	
	my $hostname = inet_ntoa(scalar(gethostbyname(hostname() || 'localhost')));
	open MAIL, "|Mail -s 'TRANSFER ERROR from $hostname' $Settings::contactEmail";
	print MAIL $row->{'TarchiveID'}."\n";
	print MAIL $row->{'ArchiveLocation'}."\n";
	close MAIL;
}
